#coding=utf8
import sys, MangaBase, re, urllib2, urlparse
import cmrhelper, decode
from cmrhelper import GbkToUtf8, UtfToGbk
class Parser(MangaBase.CMangaBase):
    "zxmh.net parser"

    def IniRe(self):
        strnamere = UtfToGbk("<title>(.*?)漫画在线看-在线漫画网</title>")
        self.namere = re.compile(strnamere)
        self.chapterre = re.compile("<li><a  target=\"_blank\" href=\"(.+?)\" >(.+?)</a></li>")
        self.pres = re.compile('</table>\r\n<script language="javascript" src=\'(/(.*?)/(.*?))\'></script>')
        self.jsre = re.compile('src=\'(.*?)\'>')
        self.cntre = re.compile('datas\[(\d*)\]')

    def ParseName(self):
        "get manga name if name is None"
        self.m_mangalog.writeLog('get manga name')
        if self.namere.findall(self.chaptercontent):
            self.m_manganame = GbkToUtf8(self.namere.findall(self.chaptercontent)[0])
            self.m_mangalog.writeLog('get manga name success, manga name [%s]' %\
                                         self.m_manganame)

    def ParseChapter(self, curl, title):
        "parse each chapter to generate url of pictures"
        try:
            content = urllib2.urlopen(curl).read()
            if self.pres.findall(content) > 0:
                "fetch the js files which show the realpath of pictures"
                jspaths = urlparse.urljoin(curl, self.pres.findall(content)[0][0])
                jssecondpath = cmrhelper.getcontent(jspaths, curl)
                jssecondpath = jssecondpath.replace('\\','')
                jssecondlist = self.jsre.findall(jssecondpath)
                jscontent = ''
                for item in jssecondlist:
                    jspaths = urlparse.urljoin(curl, item)
                    jscontent += cmrhelper.getcontent(jspaths, curl)
                # find chapter pages
                datas = [''] * (len(self.cntre.findall(jscontent)) + 1)
                # "exec the code from code"
                jscontent = jscontent.replace('var datas = new Array();\r\n', '')
                jscontent = jscontent.replace(';','')
                jscontent = jscontent.replace('var ','')
                execlist = jscontent.split('\r\n')
                for item  in execlist:
                    exec(item)
                hostname = decode.decode64(pic_path)
                for i in range(1,len(datas)):
                    purl = hostname + decode.decode64(datas[i])
                    purl = GbkToUtf8(purl)
                    self.PushPic([purl, GbkToUtf8(curl), title, self.m_manganame])
        except  Exception, e:
            self.m_mangalog.writeLog(str(e) + ' in getpiclist', 'error')

    def GetChapters(self):
        "get manga chapters"
        try:
            # first parser
            content = cmrhelper.getcontent("http://www.zxmh.net/shoucang.js",\
                                               self.m_url)
            ajaxre = re.compile("src=(.*?)><\\\/script>")
            ajaxjsurl = ajaxre.findall(content)[0].replace("\\", "")
            ajaxjsurl = ajaxjsurl.replace("\"", "")
            # parse the volume's url
            volre = re.compile("ajax\(\'(.*?)\',\'divvolumelist\'\);")
            print urlparse.urljoin(self.m_url, ajaxjsurl)
            content = cmrhelper.getcontent(urlparse.urljoin(self.m_url, ajaxjsurl),\
                                               self.m_url)
            if not content or not volre.findall(content):
                return
            content = cmrhelper.getcontent(urlparse.urljoin(self.m_url, volre.findall(content)[0]), self.m_url)
            print content
            if content and self.chapterre.findall(content):
                for item in self.chapterre.findall(content):
                    self.m_chapterlist.append([urlparse.urljoin(self.m_url, item[0]),\
                                               GbkToUtf8(item[1])])
                    self.m_chaptercnt += 1
                self.m_mangalog.writeLog('get chapters finish total: [%d] chapters'\
                                         % self.m_chaptercnt)
            else:
                self.m_mangalog.writeLog("get chapters error", 'error')
        except  Exception, e:
            self.m_mangalog.writeLog(str(e)+' in getchapter', 'error')
